package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// FranchiseController 加盟商管理控制器
type FranchiseController struct {
	web.Controller
}

// FranchiseListRequest 加盟商列表请求参数
type FranchiseListRequest struct {
	Page     int    `json:"page" form:"page"`
	PageSize int    `json:"pageSize" form:"pageSize"`
	Name     string `json:"name" form:"name"`
	Status   int8   `json:"status" form:"status"`
}

// FranchiseCreateRequest 创建加盟商请求参数
type FranchiseCreateRequest struct {
	Name        string `json:"name"`
	Logo        string `json:"logo"`
	Description string `json:"description"`
	Contact     string `json:"contact"`
	Phone       string `json:"phone"`
	Email       string `json:"email"`
	Address     string `json:"address"`
	Status      int8   `json:"status"`
	ExpireAt    int64  `json:"expire_at"`
}

// FranchiseUpdateRequest 更新加盟商请求参数
type FranchiseUpdateRequest struct {
	Name        string `json:"name"`
	Logo        string `json:"logo"`
	Description string `json:"description"`
	Contact     string `json:"contact"`
	Phone       string `json:"phone"`
	Email       string `json:"email"`
	Address     string `json:"address"`
	Status      int8   `json:"status"`
	ExpireAt    int64  `json:"expire_at"`
}

// List 获取加盟商列表
func (c *FranchiseController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	status, _ := c.GetInt8("status", -1)
	contact := c.GetString("contact")
	phone := c.GetString("phone")

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if contact != "" {
		filters["contact"] = contact
	}
	if phone != "" {
		filters["phone"] = phone
	}

	// 查询加盟商列表
	franchises, total, err := models.GetFranchiseList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取加盟商列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取加盟商列表成功",
		"data": map[string]interface{}{
			"list":  franchises,
			"total": total,
		},
	}
	c.ServeJSON()
}

// Create 创建加盟商
func (c *FranchiseController) Create() {
	// 解析请求参数
	var req FranchiseCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 创建加盟商
	franchise := &models.Franchise{
		Name:        req.Name,
		Logo:        req.Logo,
		Description: req.Description,
		Contact:     req.Contact,
		Phone:       req.Phone,
		Email:       req.Email,
		Address:     req.Address,
		Status:      req.Status,
		ExpireAt:    req.ExpireAt,
	}

	// 设置创建者信息
	franchise.CreatedBy = admin.Username
	franchise.UpdatedBy = admin.Username
	franchise.BeforeInsert()
	// 保存到数据库
	id, err := models.CreateFranchise(franchise)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建加盟商失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建加盟商成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新加盟商
func (c *FranchiseController) Update() {
	// 获取加盟商ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的加盟商ID",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req FranchiseUpdateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取加盟商信息
	franchise, err := models.GetFranchiseById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "加盟商不存在",
		}
		c.ServeJSON()
		return
	}

	// 更新加盟商信息
	franchise.Name = req.Name
	franchise.Logo = req.Logo
	franchise.Description = req.Description
	franchise.Contact = req.Contact
	franchise.Phone = req.Phone
	franchise.Email = req.Email
	franchise.Address = req.Address
	franchise.Status = req.Status
	franchise.ExpireAt = req.ExpireAt
	franchise.UpdatedBy = admin.Username
	franchise.BeforeUpdate()
	// 保存到数据库
	err = models.UpdateFranchise(franchise, "Name", "Logo", "Description", "Contact", "Phone", "Email", "Address", "Status", "ExpireAt", "UpdatedBy", "UpdatedAt")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新加盟商失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新加盟商成功",
	}
	c.ServeJSON()
}

// Delete 删除加盟商
func (c *FranchiseController) Delete() {
	// 获取加盟商ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的加盟商ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 删除加盟商
	err = models.DeleteFranchise(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除加盟商失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除加盟商成功",
	}
	c.ServeJSON()
}
